/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.knolle.vista;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import modelo.Lotes;
import modelo.UnidadMedidaSuperficie;
import org.knolle.modelo.LotesController;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.NotifyDescriptor.Confirmation;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.*;
import org.openide.util.Exceptions;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.Lookups;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.knolle.vista//ParcelasVista//EN",
autostore = false)
@TopComponent.Description(preferredID = "ParcelasVistaTopComponent",
iconBase = "org/knolle/vista/People.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
@ActionID(category = "Window", id = "org.knolle.vista.ParcelasVistaTopComponent")
@ActionReference(path = "Menu/Window" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ParcelasVistaAction",
preferredID = "ParcelasVistaTopComponent")
@Messages({
    "CTL_ParcelasVistaAction=ParcelasVista",
    "CTL_ParcelasVistaTopComponent=ParcelasVista Window",
    "HINT_ParcelasVistaTopComponent=This is a ParcelasVista window"
})
public final class ListaLotesTopComponent extends TopComponent  implements ExplorerManager.Provider {

    
    private static ExplorerManager em =  new ExplorerManager();
    private static final Integer DOBLE_CLICK = 2;
    
    public ListaLotesTopComponent() {
        initComponents();
        initComponentes();
        setName(Bundle.CTL_ParcelasVistaTopComponent());
        setToolTipText(Bundle.HINT_ParcelasVistaTopComponent());
        associateLookup(ExplorerUtils.createLookup(em, getActionMap()));
        

    }
    /**
     * Codigo generado por marcelo
     */
    private void initComponentes(){
        List<Lotes> datos = LotesController.getListaLotes();
        em.setRootContext(new AbstractNode(Children.create(new LotesChildFactory(datos), true)));
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        beanTreeView1 = new org.openide.explorer.view.BeanTreeView();

        org.openide.awt.Mnemonics.setLocalizedText(jMenuItem1, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.jMenuItem1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jMenu1, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.jMenu1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jMenu2, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.jMenu2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jMenuItem2, org.openide.util.NbBundle.getMessage(ListaLotesTopComponent.class, "ListaLotesTopComponent.jMenuItem2.text")); // NOI18N

        jScrollPane1.setViewportView(beanTreeView1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.openide.explorer.view.BeanTreeView beanTreeView1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        /**
         * COnsulta a la base de datos para ver las parcelas en esto
         */
//        GenericManager gm = new GenericManager();
        List<Lotes> lotesList = LotesController.getListaLotes();
        em.setRootContext(new AbstractNode(Children.create(new LotesChildFactory(lotesList), true)));
  
        
        
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    
    
    
    @Override
    public ExplorerManager getExplorerManager() {
        return em;
    }
    
    //LotesChildFactory
    //<editor-fold defaultstate="collapsed" desc="Codigo generado por marcelo">
    private class LotesChildFactory extends ChildFactory<Lotes> {
    
        private List<Lotes> resultList;
        
    
        public LotesChildFactory(List<Lotes> resultList) {
            this.resultList = resultList;
        }
    
        @Override
        protected boolean createKeys(List<Lotes> list) {
            for (Lotes lotes : resultList) {
                list.add(lotes);
            }
            return true;
        }
    
        @Override
        protected Node createNodeForKey(Lotes l) {
            try {
                return new LotesChildFactory.LotesBeanNode(l);
            } catch (IntrospectionException ex) {
                Exceptions.printStackTrace(ex);
                return null;
            }
        }
    
        private class LotesBeanNode extends BeanNode {
            
            private Lotes lote;
            private String PROPIEDAD_NOMBRE = "Nombre" ;
            private String PROPIEDAD_UBICACION = "Ubicacion";
            
            
            public LotesBeanNode(Lotes bean) throws IntrospectionException {
                super(bean, Children.LEAF, Lookups.singleton(bean));
                lote = bean;
            }
            
            @Override
            public String getDisplayName(){
                return lote.getNombre()+ " : "+ lote.getUbicacion();
            }
            
            
            //Metodo reescrito para mostrar otra hoja de propiedades
            //vamos a pasar a configurar las hojas de propiedades
            @Override
            protected Sheet createSheet() {
                //Crear un Sheet de propiedades
                 Sheet sheet = Sheet.createDefault();
                 
                 //Crear el set de propiedades con cada una de las propiedades del objeto
                 Sheet.Set set = Sheet.createPropertiesSet();
                 //Ahora a crear cada una de las propiedades y sus editores
                 //Por Cada Campo, crearemos un editor, y lo metemos en el set, al final metemos el set en el sheet
                 //finalmente retornamos el sheet al
                 
                 Property lotesNombreProperty = new PropertySupport.ReadOnly<String>
                         (PROPIEDAD_NOMBRE, String.class,PROPIEDAD_NOMBRE , PROPIEDAD_NOMBRE) {
                            @Override
                            public String getValue() throws IllegalAccessException, InvocationTargetException {
                            //throw new UnsupportedOperationException("Not supported yet.");
                                return lote.getNombre();
                            }
                         };
                 set.put(lotesNombreProperty);
                 sheet.put(set);
                 return sheet;
            }
            
            
            
    }

    }//</editor-fold> 
    
    //TableModel
    //<editor-fold defaultstate="collapsed" desc="Codigo generado por marcelo"> 
    private class LotesTablaModel extends AbstractTableModel{
    
    //Nombre de Columnas
    private String[] columnsName = {"id","Nombre","Superficie","Unidad","Ubicacion"};
    private List<Lotes> datos;

    /**
     * Constructor llamado y se le pasa una lista de arrays para los datos
     * @param _datos 
     */
    public LotesTablaModel(List<Lotes> _datos) {
//        System.out.print("Llamando al constructor");
        datos = _datos;
    }
    /**
     * Constructor que no inicialza los datos
     */
    public LotesTablaModel(){
       
    }
    
    @Override
    public int getRowCount() {
//        throw new UnsupportedOperationException("Not supported yet.");
        return datos.size();
    }

    @Override
    public int getColumnCount() {
//        throw new UnsupportedOperationException("Not supported yet.");
        return columnsName.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
//        throw new UnsupportedOperationException("Not supported yet."); 
        if (datos == null){
          return null;
        }
        //Hacemos un switch segun el caso
        //Rompebolisima
        try{
            Lotes lote = datos.get(rowIndex);
            switch(columnIndex) {
                case 0: return lote.getId();
                case 1: return lote.getNombre();
                case 2: return lote.getSuperficie();
                case 3: return lote.getUnidadMedidaSuperficie();
                case 4: return lote.getUbicacion();
                default: return "No hay datos para la columna seleccionada";   
            }
        }
        catch(Exception e){
           return "Se produjo un error: " + e.getMessage();
        }
        
        
        
    }

    @Override
    public String getColumnName(int column) {
        return columnsName[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch(columnIndex) {
                case 0: return Integer.class;
                case 1: return String.class;
                case 2: return BigDecimal.class;
                case 3: return UnidadMedidaSuperficie.class;
                case 4: return String.class;
                default: return String.class;
            }
        
    }
    
    
    
} //</editor-fold> 

    
}
